import { ExclamationCircleOutlined } from '@ant-design/icons';
import { message, Select } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.module.sass';

const ErrorContentNode: React.FC = () => {
    return (
        <article className={styles.errorContent}>
            <ExclamationCircleOutlined style={{ fontSize: '32px' }} />
            <section>数据获取异常</section>
        </article>
    )
}

export interface SelectOption {

    /**下拉列表项的值 */
    value: string

    /**下拉列表项展示的内容 */
    name: string
}

interface Props {
    /**远程请求函数 */
    remote: Function

    /**自定义展示模板函数 */
    template?: Function

    /**默认的提示语 */
    placeholder?: string

    /**选中 option，或 input 的 value 变化时，调用此函数 */
    onChange?: Function

    /**指定当前选中的条目 */
    value?: any

    /**设置 Select 的模式为多选或标签 */
    mode?: any

    /**下拉选择框是否可搜索 */
    isShowSearch?: boolean

    /**取消选中功能 */
    allowClear?: boolean
}

const RemoteSelect: React.FC<Props> = ({
    remote,
    template,
    placeholder,
    onChange,
    value,
    mode,
    isShowSearch,
    allowClear
}) => {
    console.debug('RemoteSelect');

    const [loading, setLoading] = useState(true);
    const [list, setList] = useState([]);
    const [errorContent, setErrorContent] = useState<any>(undefined);


    useEffect(() => {
        async function main() {
            try {
                if (loading === true) {
                    let data = await remote();
                    setList(data);
                }
            } catch (error) {
                message.error(`${placeholder}下拉列表数据加载异常`);
                setErrorContent(<ErrorContentNode />);
            } finally {
                setLoading(false);
            }
        }
        main();
    }, [remote, placeholder, loading])

    function handleChange(value: any) {
        onChange && onChange(value);
    }

    return (
        <Select
            showSearch={isShowSearch}
            className={styles.selectInput}
            placeholder={placeholder}
            loading={loading}
            onChange={handleChange}
            value={value}
            allowClear={allowClear}
            mode={mode}
            notFoundContent={errorContent}
        >
            {list.map((item: SelectOption) =>
                <Select.Option key={item.value} value={item.value}>
                    {template ? template(item) : item.name}
                </Select.Option>
            )}
        </Select>
    )
}

export default RemoteSelect;